import React, { forwardRef, useState } from "react";
import PropTypes from 'prop-types';
import { Popup, DatePicker} from "zarm";
import dayjs from "dayjs";
import { columnTypeMap } from "../../utils";

const PopupDate = forwardRef(({ onSelect, mode = 'date'},ref) => {
    const [show, setShow] = useState(false)
    const [now, setNow] = useState(new Date())
    
    const choseMonth = (value) => {
        setNow(value)
        setShow(false)
        if (mode == 'month') {
            onSelect(dayjs(value).format('YYYY-MM'))
        } else if (mode == 'date') {
            onSelect(dayjs(value).format('YYYY-MM-DD'))
        }
        
    }

    if (ref) {
        ref.current = {
            show: () => {
                setShow(true)
            },
            close: () => {
                setShow(false)
            }
        }
    }

    return <Popup
        visible={show}
        direction="bottom"
        onMaskClick={() => setShow(false)}
        destroy={false}
        mountContainer={() => document.body}
    >
        <div>
            <DatePicker
                visible={show}
                value={now}
                columnType={columnTypeMap[mode]}
                onConfirm={(value) => choseMonth(value)}
                onCancel={() => setShow(false)}
            />
        </div>

    </Popup>

})

PopupDate.propTypes = {
    mode: PropTypes.string,
    onSelect: PropTypes.func
}

export default PopupDate
